<?php


namespace App\Services;


use Illuminate\Support\Facades\DB;

class MemberService
{
    const BalanceTypeLy = 1; // 乐游币
    const BalanceTypeJf = 2; // 积分
    const BalanceTypeWf = 3; // 玩服积分
    const BalanceTypeWf1 = 4; // 每日领取玩服积分
    const BalanceTypered = 5; // 红包币
     const BalanceTypetotal = 6; // 累计积分



    const NewRedPacketCoin = 10; // 新红包币


    const FromTypeRecharge = 1; // 充值
    const FromTypeDh = 2; // 兑换
    const FromTypeDhGoods = 3; // 兑换商品
    const FromTypeReward = 4; // 下级奖励
    const FromTypeRealName = 5; // 实名认证
    const FromTypeBindMobile = 6; // 手机号绑定
    const FromTypeSubBindMobile = 7; // 下级手机号绑定
    const FromTypeSubRealName = 8; // 下级实名
    const FromTypeAdmin = 9; // 管理员修改
    const FromTypeGameActivity = 10; // 游戏活动送
    const FromTypeLBActivity = 11; // 老兵活动送
    const FromTypeFiveDayActivity = 12; // 5日签到活动
    public static function setMemberBalance($userInfo, $balanceType, $fromType, $fromId, $change, $remark)
    {
        if ($change == 0) {
            return;
        }
        if (!$userInfo->wx_unionid || !$userInfo->unionid) {
            throw new \Exception('unionid错误');
        }
        $field = '';
        switch ($balanceType) {
            case self::BalanceTypeLy:
                $origin = $userInfo->ly_balance;
                $field = 'ly_balance';
                break;
            case self::BalanceTypered:
                $origin = $userInfo->red_packet_coin;
                $field = 'red_packet_coin';
                break;
            case self::BalanceTypeJf:
                $origin = $userInfo->integral;
                $field = 'integral';
                break;
            case self::BalanceTypeWf:
                $origin = $userInfo->wf_integral;
                $field = 'wf_integral';
                break;
            case self::NewRedPacketCoin:
                $origin = $userInfo->new_red_packet_coin;
                $field = 'new_red_packet_coin';
                break;
            default:
                return;
        }
        // 防抖， 防止负数

        $update = DB::table('users')->where('id', $userInfo->id)->where($field, $origin);
        if ($change < 0) {

            $update->where($field, '>=', -$change);
        }
        if (!$update->increment($field, $change)) {
            throw new \Exception('更新余额失败');
        }
        if($balanceType==5){
            $remark=$remark. $_SERVER['HTTP_HOST'] ;
        }
        // 写用户币记录
        $balanceLog = [
            'union_id' => $userInfo->wx_unionid,
            'unionid' => $userInfo->unionid,
            'balance_type' => $balanceType,
            'from_type' => $fromType,
            'from_id' => $fromId,
            'origin' => $origin,
            'change'  => $change,
            'now' => (int)$origin+$change,
            'remark' => $remark,
            'create_time' => time()
        ];
        if (!DB::table('user_balance_log')->insert($balanceLog)) {
            throw new \Exception('创建更新日志失败');
        }
        return;
    }

    /**
     * 刷新等级
     * @param $userInfo
     */
    public static function refreshLevel($userInfo)
    {
        if (empty($userInfo->unionid)) {
        return;
         }

        $oldLevel = $userInfo->level_id;

        $total = DB::connection('game_db')->table('转区')
            ->where('标签', $userInfo->unionid)
            ->value('累计积分');
        if (!$total || $total <= 0) {
            $total = 0;
        }

        $totalDeduction = DB::table('user_growth_log')
                ->where('unionid', $user->unionid)
                ->where('change_type', '1')
                ->sum('change_amount');

            $totalDeduction = abs($totalDeduction);
            $total = $gameUser->累计积分;
            $remainingTotal = $total - $totalDeduction;

            if ($remainingTotal > 30) {
                $totalRecharges = $remainingTotal;
            } else {
                $totalRecharges = 30;
            }

        // 根据最新的成长值更新用户等级
        $level = DB::table('user_level')->where('need_money', '<=', $totalRecharges)
            ->orderBy('need_money', 'desc')->first();
        if (!$level) {
            return response()->json(['message' => 'No level found.'], 400);
        }

        $existingLog = DB::table('user_growth_log')
            ->where('unionid', $userInfo->unionid)
            ->whereDate('create_date', now()->toDateString())
            ->exists();

        if (!$existingLog) {
            // 更新users表中的数据
            DB::table('users')->where('id', $userInfo->id)
                ->update([
                    'level_id' => $level->id,
                    'cumulative_points' => $total,
                    'total_recharge' => $totalRecharges,
                    'updated_at' => now(), // 更新最后一次修改时间
                    'processed_at' => now(), // 更新处理时间
                ]);

            // 记录日志
            DB::table('user_growth_log')->insert([
                'unionid' => $userInfo->unionid,
                'change_amount' => -$deductionAmount,
                'change_type' => '1',
                'create_time' => now(),
                'create_date' => now()->toDateString(), // 确保插入 create_date 列
            ]);
        }
            // 更新客服
            $userUpgrade = [
                'unionid'=>$userInfo->unionid,
                'old_level' => $oldLevel,
                'new_level' => $level->id,
                'create_time' => date('Y-m-d H:i:s')
            ];
            if ($oldLevel < $level->id) {
                $customServiceUser = DB::table('custom_service_user')->where('unionid', $userInfo->unionid)->first();
                if ($customServiceUser) {
                    $kf = DB::table('custom_service')->find($customServiceUser->service_id);
                    $kfLevel = DB::table('custom_service_level')->find($kf->level_id);
                    $rewardMap = json_decode($kfLevel->reward);
                    if ($kf) {
                        if(!($kf->start_vip > $level->id || $kf->end_vip < $level->id)) {
                            $userUpgrade['customer_service_id'] = $kf->id;
                            $userUpgrade['reward'] = $rewardMap[$level->id] ?? 0;
                        }
                    }
                }
            }
            DB::table('user_upgrade_log')->insert($userUpgrade);
            return;
    }

    /**
     * 绑定客服
     * @param $unionId
     * @param $adminId
     * @param $bindType
     * @return bool|string
     * @throws \Exception
     */
    public static function bindCustomService($unionId, $adminId, $bindType)
    {
        $userInfo = DB::table('users')->where('unionid', $unionId)->first();
        if (!$userInfo) {
            throw new \Exception('用户信息错误');
        }
        $ctmSer = DB::table('customer_service')->find($adminId);
        if (!$ctmSer) {
            throw new \Exception('客服信息错误');
        }
        $kfLevel = DB::table('customer_service_level')->find($ctmSer->level_id);
        if($kfLevel->start_vip > $userInfo->level_id || $kfLevel->end_vip < $userInfo->level_id) {
            throw new \Exception('VIP等级无法绑定此客服');
        }
        $bindLog = DB::table('customer_service_user')
            ->where('unionid',$unionId)
            ->first();
        $data = [
            'unionid' => $unionId,
            'service_id' => $adminId,
            'bind_type' => $bindType,
            'create_time' => date('Y-m-d H:i:s')
        ];
        if ($bindLog) {
            if ($bindLog->server_id == $adminId) {
                throw new \Exception('重复绑定');
            }
            $id = DB::table('customer_service_user')->where('id', $bindLog->id)
                ->update($data);
        } else {
            if (!$id = DB::table('customer_service_user')->insert($data)) {
                throw new \Exception('绑定失败');
            }
        }
        return $id;
    }


    /**
     * 获取老兵活动奖励
     * @return \int[][]
     */
    public static function getLbActivateConf()
    {
        return [
            8 => [50,70,100,130,160,190,220],
            9 => [70,100,150,200,250,300,350],
            10 => [100,150,200,250,300,350,400],
            11 => [150,200,300,450,600,750,900],
            12 => [200,300,400,500,600,700,800],
            13 => [300,400,500,600,700,800,900],
            14 => [350,450,550,650,750,850,950],
            15 => [400,500,600,700,800,900,1000],
            16 => [450,500,650,750,850,950,1050],
            17 => [500,600,700,800,900,1000,1100],
            18 => [600,700,800,900,1000,1100,1200],
            19 => [700,800,900,1000,1100,1200,1300],
            20 => [800,900,1000,1100,1200,1300,1400],
            21 => [900,1000,1100,1200,1300,1400,1500],
            22 => [1000,1100,1200,1300,1400,1500,1600],
            23 => [1200,1300,1400,1500,1600,1700,1800],
            24 => [1400,1500,1600,1700,1800,1900,2000],
        ];
    }

    /**
     * 获取节日
     * @return string[]
     */
    public static function getFestival()
    {
        return [
            1 => '春节',
            2 => '端午节',
            3 => '中秋节',
        ];
    }
}

